import logging

import pytest

from class_04.p04_intfPytestAuto.api_keyword.api_key import ApiKey


# 项目级的fix，可以进行全项目的接口关联，整个项目这个fix只运行一次

@pytest.fixture(scope="session")
def token_fix():
    # 初始化工具类
    ak=ApiKey()
    # 完成登录，并返回token
    data = {
        "accounts": "hu2374145",
        "pwd": "hu2374145",
        "type": "username"
    }
    params = {
        "application": "app",
        "application_client_type": "weixin"
    }
    url = "http://shop-xo.hctestedu.com/index.php?s=api/user/login"
    res_login = ak.post(url=url,  json=data, params=params)
    token = ak.get_text(res_login.text, '$..token')
    return ak,token


# 避免日志乱码
def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台
    :param items:
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        # 在控制台输出未转码的nodeid
        # print(item.nodeid)
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")

# 日志工具类
@pytest.hookimpl(hookwrapper=True,tryfirst=True)
def pytest_runtest_makereport(item,call):
    out = yield # 获取函数的调用结果
    print('out',out)
    res = out.get_result() # 从日志获取测试报告
    print('res',res)
    if res.when == "call":
        logging.info(f"用例ID:{res.nodeid}")
        logging.info(f"测试结果:{res.outcome}")
        logging.info(f"故障表示:{res.longrepr}")
        logging.info(f"异常:{call.excinfo}")
        logging.info(f"用例耗时:{res.duration}")
        logging.info("************************")

